package com.collect.tanzania.zhiScene.zhiWidget.zhiInputView;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.SpannableString;
import android.text.SpannedString;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.collect.tanzania.R;
import com.collect.tanzania.zhiUtils.StringUtil;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;

@SuppressLint("NonConstantResourceId")
public class ZHIInputEditView extends LinearLayout implements View.OnClickListener, View.OnFocusChangeListener, TextWatcher {
    private final Context mContext;

    private String hintText;
    private String inputtype;
    private int maxLength;
    private int editlogo;
    private boolean hasClear;
    private boolean hasSeePwd;
    private int type = InputType.TYPE_CLASS_TEXT;

    private View mView;

    private ZHIInputEditViewTextChangedListener onTextDidChangedListener;

    @BindView(R.id.iv_editinput_icon)
    ImageView mIcon;
    @BindView(R.id.et_editinput)
    EditText etInput;
    @BindView(R.id.iv_editinput_del)
    ImageView mDel;
    @BindView(R.id.iv_editinput_see)
    ImageView mSee;

    public ZHIInputEditView(Context context) {
        this(context, null);
    }

    public ZHIInputEditView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ZHIInputEditView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        this.mContext = context;

        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CFInputEditView);
        editlogo = ta.getResourceId(R.styleable.CFInputEditView_editlogo, R.mipmap.ic_launcher);
        hintText = ta.getString(R.styleable.CFInputEditView_hintText);

        inputtype = ta.getString(R.styleable.CFInputEditView_inputtype);
        maxLength = ta.getInt(R.styleable.CFInputEditView_maxLength, 64);
        type = getType(inputtype);
        hasClear = ta.getBoolean(R.styleable.CFInputEditView_hasClear, true);
        hasSeePwd = ta.getBoolean(R.styleable.CFInputEditView_hasSeePwd, false);
        ta.recycle();

        initContentView();
        initView();
    }

    private int getType(String inputtype) {
        if (inputtype.equals("number")) {
            return InputType.TYPE_CLASS_NUMBER;
        } else if (inputtype.equals("textPassword")) {
            return InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
        } else if (inputtype.equals("phone")) {
            return InputType.TYPE_CLASS_PHONE;
        } else {
            return InputType.TYPE_CLASS_TEXT;
        }
    }

    private void initContentView() {
        mView = View.inflate(mContext, R.layout.view_input_edit, this);
        ButterKnife.bind(this);
    }

    // 初始化页面，根据设置项显示
    private void initView() {

        mIcon.setVisibility(View.GONE);
        mIcon.setImageResource(editlogo);
        SpannableString ss = new SpannableString(hintText);
        etInput.setHint(new SpannedString(ss));
        etInput.setInputType(type);
        etInput.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
        mView.setOnClickListener(this);

        etInput.setOnFocusChangeListener(this);
        etInput.addTextChangedListener(this);
        if (type != InputType.TYPE_CLASS_TEXT) {
            etInput.setKeyListener(DigitsKeyListener.getInstance("1234567890"));
        }

        if (hasClear) {
            mDel.setOnClickListener(this);
        }

        mDel.setVisibility(View.INVISIBLE);
        if (hasSeePwd) {
            mSee.setVisibility(View.VISIBLE);
            mSee.setOnClickListener(this);
        } else {
            mSee.setVisibility(View.GONE);
        }

        etInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
//                if(true == etInput.getText().toString().trim().startsWith("0")){
//                    etInput.setText("");
//                    return;
//                }
                if (onTextDidChangedListener != null) {
                    onTextDidChangedListener.OnTextDidChanged();
                }
            }
        });
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_editinput:
                etInput.setFocusableInTouchMode(true);
                etInput.requestFocus();
                break;
            case R.id.iv_editinput_del:
                //清空密码
                etInput.setText(null);
                break;
            case R.id.iv_editinput_see:
                if (mSee.isSelected()) {
                    mSee.setSelected(false);
                    etInput.setTransformationMethod(PasswordTransformationMethod.getInstance());
                } else {
                    mSee.setSelected(true);
                    etInput.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }
                etInput.setSelection(etInput.getText().length());
                break;
            default:
                break;
        }
    }

    //用户名密码焦点改变
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        int id = v.getId();

        if (id == R.id.et_editinput) {
            if (hasFocus) {
                etInput.setActivated(true);
                mView.setActivated(false);
            }
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    //用户名密码输入事件
    @Override
    public void afterTextChanged(Editable s) {
        if (hasClear) {
            //是否显示清除按钮
            String text = etInput.getText().toString().trim();
            if (text.length() > 0) {
                mDel.setVisibility(View.VISIBLE);
            } else {
                mDel.setVisibility(View.INVISIBLE);
            }
        }

        if (onTextDidChangedListener != null) {
            onTextDidChangedListener.OnTextDidChanged();
        }

    }

    public void setOnTextDidChangedListener(ZHIInputEditViewTextChangedListener onTextDidChangedListener) {
        this.onTextDidChangedListener = onTextDidChangedListener;
    }

    public String getText() {
        return etInput.getText().toString().trim();
    }

    public String getTextTrimAll() {
        return StringUtil.trimAll(etInput.getText().toString().trim());
    }

    public void setText(String text) {
        etInput.setText(text);
        etInput.setSelection(text.length());
    }

    public String getHintText() {
        return hintText;
    }

    public void setBeFocusing() {
        etInput.setFocusableInTouchMode(true);
        etInput.setFocusable(true);
        etInput.requestFocus();

        etInput.findFocus();
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(etInput, InputMethodManager.SHOW_FORCED);// 显示输入法
    }

    public void setPasswordInputFilter() {
        InputFilter filter = (source, start, end, dest, dstart, dend) -> {
            for (int i = start; i < end; i++) {
                Character gchar = new Character(source.charAt(i));
                String gcharStr = gchar.toString();

                String sets = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
                if (!sets.contains(gcharStr)) {
                    return "";
                }
            }
            return null;
        };
        if (etInput != null) {
            etInput.setFilters(new InputFilter[]{new InputFilter.LengthFilter(15), filter});
        }
    }

    public boolean checkPasswordInputValid() {
        String gpwd = getTextTrimAll();

        if (gpwd.length() < 8) {
            return false;
        }

        if (gpwd.length() > 15) {
            return false;
        }

        Matcher matcher = Pattern.compile(".*[a-zA-Z0-9]+.*").matcher(gpwd);
        return matcher.matches();

//        Boolean b = gpwd.matches(".*?[a-zA-Z]+.*?") && gpwd.matches(".*?[\\d]+.*?");
//        return b;
//        Pattern p = Pattern.compile(strPattern);
//        //判断Str是否匹配，返回匹配结果
//        Matcher m = p.matcher(gpwd);
//        return m.find();
    }

}
